<template>
  <el-dialog
    v-el-drag-dialog
    title="新增盘点"
    :visible.sync="visible"
    width="1200px"
    @closed="reset"
  >
    <el-form ref="dataForm" :model="form" class="form" :rules="rules" label-position="right" label-width="90px">
      <el-form-item label="盘点仓库:" prop="storeId">
        <el-select
          v-model="form.storeId"
          filterable
          placeholder="请选择"
          @change="changeStoreId"
        >
          <el-option
            v-for="item in storeMap"
            :key="item.storeId"
            :label="item.storeName"
            :value="item.storeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="盘点人员:" prop="name">
        <el-input :value="userInfo.userName" placeholder="请输入" disabled />
      </el-form-item>
      <el-form-item label="盘点日期:">
        <el-date-picker v-model="form.date" type="date" disabled style="width: 100%;" />
      </el-form-item>
      <el-form-item label="备注:" prop="name" class="block">
        <el-input v-model.trim="form.remark" :maxlength="250" placeholder="请输入" />
      </el-form-item>
      <!-- <el-form-item label="商品类型:" prop="csmTypeSource">
        <el-tree-select
          v-model="shop.gtId"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          disabled
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'gtId',
              label: 'gtName',
              disabled: 'disabled',
            },
            data: goodsTreeData,
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item> -->
      <el-form-item label="规格型号:">
        <el-select
          v-model="shop.specCode"
          placeholder="请选择"
          @change="selectGoods"
        >
          <el-option
            v-for="(l, i) in goodsTypesDetailList"
            :key="i"
            :value="l.specCode"
            :label="l.specName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label-width="10px">
        <el-button type="primary" icon="el-icon-plus" @click="add">添加</el-button>
      </el-form-item>
    </el-form>
    <lb-table
      ref="lbTable"
      class="table"
      border
      height="350"
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      @selection-change="handleSelectionChange"
    />
    <div slot="footer" class="dialog-footer">
      <el-button @click="reset"> 关闭 </el-button>
      <el-button type="primary" @click="save"> 保存 </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import {
    goodsTypeQueryList,
    goodsTypeDetail,
    queryMap,
    repertoryStoreAdd,
    repertoryStoreDeatil
  } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import { formatColumnMap } from '@/utils'
  export default {
    name: 'add',
    props: ['storeMap'],
    data() {
      return {
        visible: false,
        form: {
          date: new Date()
        },
        rules: {
          storeId: [{ required: true, message: '请选择盘点仓库', trigger: 'change' }]
        },
        statusMap: [],
        uuid: 1,
        selectTableData: [],
        goodsDetail: {},
        goodsTypesDetailList: [],
        goodsTreeData: [],
        gtObj: {},
        shop: {
          specCode: null,
          gtId: null
        },
        tableData: {
          column: [
            {
              type: 'selection'
            },
            // {
            //   prop: 'gtName',
            //   width: 120,
            //   label: '商品类型'
            // },
            // {
            //   prop: 'goodsName',
            //   width: 150,
            //   label: '商品名称',
            //   renderHeader: (h, { row }) => {
            //     return (
            //     <el-tooltip
            //       class='item'
            //       effect='dark'
            //       content='默认加载仓库中有数据的商品，可在上方选择其他商品点击添加'
            //       placement='top-start'
            //     >
            //       <i class='el-icon-question'>
            //         <span>商品名称</span>
            //       </i>
            //     </el-tooltip>
            //     )
            //   }
            // },
            {
              prop: 'goodsSpec',
              label: '规格型号'
            },
            {
              prop: 'gdStatus',
              width: 110,
              label: '状态',
              render: (h, scope) => (
              <div>
                {scope.row._edit && !scope.row.storeName && scope.row.gtFlag ? (
                  <el-select
                    value={scope.row[scope.column.property]}
                    onChange={(val) => {
                      scope.row[scope.column.property] = val
                    }}
                  >
                    {scope.row.statusMap.map((option) => {
                      return (
                        <el-option label={option.desc} value={option.value}></el-option>
                      )
                    })}
                  </el-select>
                ) : (
                  <span>
                    {scope.row.gdStatus &&
                      formatColumnMap(
                        this.statusMap,
                        'value',
                        scope.row.gdStatus,
                        'desc'
                      )}
                  </span>
                )}
              </div>
            )
            },
            {
              prop: 'gdCount',
              align: 'right',
              label: '账面库存',
              render: (h, { row }) => {
                return <span>{row.gdCount }{row.unitName}</span>
              }
            },
            {
              prop: 'realCount',
              align: 'right',
              label: '实际库存',
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <el-input-number
                      controls={false}
                      min={0}
                      max={99999}
                      precision={0}
                      value={scope.row[scope.column.property]}
                      onInput={(val) => {
                        scope.row[scope.column.property] = val
                      }}
                    ></el-input-number>
                  ) : (
                    <span>{scope.row[scope.column.property]}</span>
                  )}
                </div>
                )
              }
            },
            {
              label: '盈/亏数量',
              align: 'right',
              render: (h, { row, $index }) =>
                (row.realCount || row.realCount === 0) && (row.gdCount || row.gdCount === 0)
                  ? row.realCount - row.gdCount === 0 ? (
                <span></span>
                    ) : (
                <span style='color:red'>
                  {row.realCount - row.gdCount > 0
                    ? '+' + (row.realCount - row.gdCount)
                    : row.realCount - row.gdCount}
                </span>
              )
                  : ''
            },
            {
              prop: 'remark',
              width: 200,
              label: '备注',
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <el-input
                      value={ scope.row[scope.column.property] }
                      onInput={(val) => {
                        scope.row[scope.column.property] = val
                      }}
                    ></el-input>
                  ) : (
                    <span>{scope.row[scope.column.property]}</span>
                  )}
                </div>
                )
              }
            },
            {
              label: '操作',
              width: 80,
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <div>
                      <el-link
                        underline={false}
                        onClick={() => {
                          this.handleSave(scope)
                        }}
                      >
                        保存
                      </el-link>
                      <el-link
                        underline={false}
                        onClick={() => {
                          this.handleCancle(scope)
                        }}
                      >
                        取消
                      </el-link>
                    </div>
                  ) : (
                    <el-link
                      underline={false}
                      onClick={() => {
                        this.handleEdit(scope)
                      }}
                    >
                      编辑
                    </el-link>
                  )}
                </div>
                )
              }
            }
          ],
          data: [],
          defaultData: []
        }
      }
    },
    computed: {
      ...mapGetters(['corpSettingData', 'userInfo'])
    },
    methods: {
      async open(row) {
        await this.getGoodsTreeData()
        await this.getGoodStatus()
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
        })
      },
      // 获取商品状态枚举
      async getGoodStatus() {
        //  GdStatus
        const res = await queryMap({ enumName: 'GdStatus' })
        this.statusMap = res.data
      },
      // 获取商品分类树
      async getGoodsTreeData() {
        const res = await goodsTypeQueryList({})
        const data = res.data.map((item) => ({
          label: item.gtName,
          ...item
        }))
        this.goodsTreeData = getTreeData(data, 'parentId', 'gtId')
        let temp
        if (res.data && res.data.length > 0) {
          for (let i = 0; i < res.data.length; i++) {
            const node = res.data[i]
            if (node.gtFlag && node.gtFlag === 2) {
              this.shop.gtId = node.gtId // 默认选中气瓶
              temp = node
              break
            }
          }
        }
        this.selectTreeChange(temp)
      },
      // 选择商品分类
      async selectTreeChange(value) {
        this.gtObj = { ...value }
        this.shop.specCode = ''
        if (value) {
          await this.getGoodsTypeDetails(value.gtId)
        }
      },
      // 获取商品分类详情
      async getGoodsTypeDetails(val) {
        try {
          const res = await goodsTypeDetail({ gtId: val })
          if (res.exc != null) {
            this.$messsage.error('查询异常')
            return
          } else if (!res.data) {
            this.$messsage.error('没有查询到相关数据')
            return
          }
          var array = []
          if ((this.corpSettingData.sp3 >> 6) & 0x01) {
            array = array.concat(
              res.data.rows.filter(function(item) {
                if (!item.options) {
                  return true
                }
                if ((item.options >> 1) & 0x01) {
                  return false
                }
                if ((item.options >> 2) & 0x01) {
                  return false
                }
                return true
              })
            )
          } else {
            if (this.gtObj && this.gtObj.gtFlag === 1) {
              array = array.concat(
                res.data.rows.filter(function(item) {
                  return item.pricingMode === 2
                })
              )
            } else {
              array = array.concat(res.data.rows)
            }
          }

          this.goodsTypesDetailList = [...array]
        } catch (error) {
          console.log(error)
        }
      },
      // 查询库存详情
      async changeStoreId(val) {
        const params = {
          storeId: val
          // currentPage: 1,
          // pageSize: 999,
          // sortBy: -1
        }
        const res = await repertoryStoreDeatil(params)
        const list = []
        const rows = res.data
        for (let i = 0; i < rows.length; i++) {
          if (!rows[i].gdCount && (!rows[i].netWeight || rows[i].netWeight * 1 === 0)) {
            continue
          }
          if (rows[i].pricingMode === 2) {
            rows[i].gdCount = rows[i].netWeight
            rows[i].realCount = rows[i].gdCount
          } else {
            rows[i].realCount = rows[i].gdCount
          }
          list.push(rows[i])
        }
        // var list = res.data.rows.map(l => {
        //   // if(l.pricingMode == 2) {
        //   //   l.g
        //   // }
        //   return { ...l, gdCount: l.netWeight * 1, realCount: l.netWeight * 1, remark: null }
        // })
        const temp = JSON.parse(JSON.stringify(list)).map(item => {
          return {
            ...item,
            remark: ''
          }
        })
        this.tableData.data = temp
        this.tableData.defaultData = JSON.parse(JSON.stringify(temp))
        // this.$set(this.tableData, 'data', temp)
        // this.$set(this.tableData, 'defaultData', JSON.parse(JSON.stringify(temp)))
      },

      // 添加商品
      addShop() {
        var { gtId, goodsId, specCode, gdCount } = this.temp
        if (!(specCode && gdCount)) {
          this.$message.warning('请完整商品属性')
          return
        }
        var goodsName = this.goodsTypesDetailList.find(
          (l) => l.specCode === this.temp.specCode
        ).goodsName
        var item = this.tableData.data.find((l) => l.specCode === this.temp.specCode)
        if (item) {
          item.gdCount++
        } else {
          var obj = {
            gdCount: '1',
            gdStatus: 2,
            specCode: specCode,
            goodsId: goodsId,
            goodsName: goodsName,
            gtId: gtId,
            gtName: '气瓶',
            rowid: new Date() * 1
          }
          this.tableData.data.push(obj)

        // this.tableData.data = [...this.tableData.data, { gtName: this.temp.gtName, goodsName: this.temp.goodsName, gdCount: this.temp.gdCount }]
        }
      },
      // 删除商品
      del(row, index) {
        const vm = this
        vm.$confirm('是否将该商品移除列表?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.tableData.data.splice(index, 1)
          // this.$message.success('删除成功')
          })
          .catch((e) => {
          // this.$message.info('已取消删除操作')
          })
      },
      selectGoods(val) {
        var obj = this.goodsTypesDetailList.find((l) => l.specCode === val)
        this.goodsDetail = { ...obj }
      },
      // 当前选择的表格行
      handleSelectionChange(val) {
        this.selectTableData = val
      },
      add() {
        if (!(this.shop.specCode)) {
          this.$message.warning('请选择商品')
          return
        }

        const selectedGd = this.goodsDetail
        var row = {
          uuid: ++this.uuid,
          goodsId: selectedGd.goodsId,
          goodsName: selectedGd.goodsName,
          gtId: selectedGd.gTypeId,
          gtName: selectedGd.gtName,
          gtSNNo: selectedGd.gtSNNo,
          gtFlag: this.gtObj.gtFlag,
          pricingMode: selectedGd.pricingMode,
          goodsCode: selectedGd.goodsCode,
          specCode: selectedGd.specCode,
          goodsSpec: selectedGd.specName,
          unitId: selectedGd.unitId,
          unitName: selectedGd.unitName || 0,
          goodStatus: selectedGd.gdStatus,
          gdCount: 0,
          realCount: 0,
          lessCount: 0,
          netWeight: 0,
          realNetWeight: 0,
          remark: null,
          statusMap: [],
          gdStatus: null,
          _edit: true
        }
        row.statusMap = this.setGdStatusMap(row)
        console.log(row)
        this.tableData.data.push(row)
        this.tableData.defaultData.push(row)
        this.$refs.lbTable.toggleRowSelection(row) // 默认添加选中
      },
      setGdStatusMap(row) {
        if (this.corpSettingData.sp3 >> 6 & 0x01) {
          if (row.pricingMode === 2) {
            return [{ value: 6, desc: '正常' }]
          } else {
            const datas = this.statusMap
            if (row.goodStatus) {
              const realItems = []
              for (var i in datas) {
                const item = datas[i]
                if ((row.goodStatus & 1 << item.value) > 0) {
                  realItems.push(item)
                }
              }
              return realItems
            } else {
              return datas
            }
          }
        } else {
          if (row.gtFlag === 3 || row.pricingMode === 2) {
            return [{ value: 6, desc: '正常' }]
          } else if (row.gtFlag <= 2) {
            const datas = this.statusMap
            if (row.goodStatus) {
              const realItems = []
              // eslint-disable-next-line no-redeclare
              for (var i in datas) {
                const item = datas[i]
                if ((row.goodStatus & 1 << item.value) > 0) {
                  realItems.push(item)
                }
              }
              console.log('realItems', realItems)
              return realItems
            } else {
              return datas
            }
          }
        }
      },
      lessCountFormat(r) {
        var lessCount = r.realCount - r.gdCount
        if (!lessCount) {
          return ''
        }
        if (r.pricingMode === 2) {
          lessCount = Number(lessCount).toFixed(2)
        }
        return lessCount > 0 && !lessCount ? lessCount : ''
      },
      handleEdit(scope) {
        if (scope.row.gdStatus) {
          this.$set(
            scope.row,
            'statusMap',
            this.statusMap
          )
        } else {
          this.$set(
            scope.row,
            'statusMap',
            this.statusMap
          )
        }

        this.$set(scope.row, '_edit', true)
      },
      handleSave(scope) {
        this.$set(scope.row, '_edit', false)
        this.$set(
          this.tableData.defaultData,
          scope.$index,
          JSON.parse(JSON.stringify(scope.row))
        )
      },
      handleCancle(scope) {
        this.tableData.data[scope.$index] = JSON.parse(
          JSON.stringify(this.tableData.defaultData[scope.$index])
        )
        scope.row._edit = false
      // this.$set(
      //   this.tableData.data,
      //   scope.$index,
      //   JSON.parse(JSON.stringify(this.tableData.defaultData[scope.$index]))
      // )
      },

      async save() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          var storeId = this.form.storeId
          var storeName = this.storeMap.find((l) => l.storeId === this.form.storeId)
            .storeName
          var createUser = this.userInfo.userName
          if (!createUser) {
            this.$message.error('请输入盘点人员')
            return
          }

          var remark = this.form.remark
          var rows = this.selectTableData
          if (!rows || !rows.length) {
            this.$message.error('请选择需盘点商品')
            return
          }
          var specCodeObj = {} // 判断某种状态的商品是否重复 { specCode: [gdStatus1, gdStatus2] }
          for (var i = 0; i < rows.length; i++) {
            var row = rows[i]
            if (!row.gdStatus) {
              this.$message.error(this.StringFormat('请选择{0}的状态', row.goodsSpec))
              return
            }
            if (row._edit) {
              this.$message.error(this.StringFormat('请先保存{0}（{1}）', row.goodsSpec, this.statusFormat(row.gdStatus).desc))
              return
            }
            if (!specCodeObj[row.specCode]) {
              specCodeObj[row.specCode] = [row.gdStatus * 1]
            } else {
              console.log(specCodeObj[row.specCode], 'specCodeObj[row.specCode]')
              if (specCodeObj[row.specCode].find((l) => l === row.gdStatus * 1)) {
                console.log(row.gdStatus, this.statusFormat(row.gdStatus).desc, '000000')
                this.$message.error(
                  this.StringFormat(
                    '{0}（{1}）已存在',
                    row.goodsSpec,
                    this.statusFormat(row.gdStatus).desc
                  )
                )
                return
              } else {
                specCodeObj[row.specCode].push(row.gdStatus * 1)
              }
            }
            console.log(row, '000000000000')
            if (!(row.realCount || row.realCount * 1 === 0)) {
              this.$message.error(
                this.StringFormat(
                  '请输入{0}的实际库存',
                  row.goodsSpec,
                  this.statusFormat(row.gdStatus)
                )
              )
              return
            }
            if (row.storeName && (row.realCount >= 0 || row.gdCount >= 0)) {
              if (!row.gdCount) row.gdCount = 0
              if (row.realCount * 1 !== row.gdCount * 1) {
                if (!row.remark) {
                  this.$message.error(
                    this.StringFormat(
                      '{0}的账面库存和实际库存不相等，请在备注里写明原因',
                      row.goodsSpec,
                      this.statusFormat(row.gdStatus)
                    )
                  )
                  return
                }
              }
            }
          }
          var newRows = []
          for (i = 0; i < rows.length; i++) {
            var obj = { ...rows[i] }
            // if (obj.pricingMode === 2) {
            //   obj.netWeight = obj.realCount
            //   obj.gdCount = 0
            //   obj.realCount = 0
            // } else {
            //   obj.gdCount = obj.realCount
            // }
            // delete obj.realCount
            // delete obj.realNetWeight
            newRows.push(obj)
          }
          var checkBill = {
            storeId: storeId,
            storeName: storeName,
            remark: remark,
            detailList: newRows
          }

          this.$confirm('盘点影响库存，请确认盘点数量是否正确？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.submit(checkBill)
          }).catch(() => {
            console.log('已取消')
          })
        })
      },
      async submit(checkBill) {
        const res = await repertoryStoreAdd(checkBill)
        if (res.exc != null) {
          this.$message.error(res.exc || '操作异常')
          return
        }
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: res.data,
          type: 'success',
          duration: 2000
        })
      },
      StringFormat(B) {
        var A = Array.prototype.slice.call(arguments, 1)
        return B.replace(/\{(\d+)\}/g, function(C, D) {
          return A[D]
        })
      },
      statusFormat(val) {
        console.log(this.statusMap)
        var msg = this.statusMap.find(item => item.value === val)
        return msg || {}
      },
      reset() {
        this.tableData.data = []
        this.form.remark = ''
        this.$refs.dataForm.resetFields()
        this.shop = {
          specCode: null,
          gtId: null
        }
        this.visible = false
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 33%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
.table {
  /deep/ .cell .el-input-number--small {
    width: 85px;
  }
}
</style>
